package com.org.service.impl;

import com.org.entity.Users;
import com.org.entity.bo.UserBO;
import com.org.enums.Sex;
import com.org.mapper.UsersMapper;
import com.org.service.UserService;
import com.org.utils.DateUtil;
import com.org.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tools.n3r.idworker.Sid;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private Sid sid;


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean queryUserNameIsExist(String username) {

        Example userExample=new Example(Users.class);
        Example.Criteria usercriteria=userExample.createCriteria();
        usercriteria.andEqualTo("username",username);
        Users result=usersMapper.selectByPrimaryKey(userExample);

        return result==null?false:true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBO userBO) {

        String userId=sid.nextShort();

        Users users=new Users();
        users.setId(userId);
        users.setUsername(userBO.getUsername());
        try {
            users.setPassword(MD5Utils.getMDStr(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        users.setNickname(userBO.getUsername());
        users.setFace("");
        users.setBirthday(DateUtil.stringToDate("2000-01-01"));
        users.setSex(Sex.secret.type);
        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());

        usersMapper.insert(users);
        return users;

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String password) {

        Example userExample=new Example(Users.class);
        Example.Criteria usercriteria = userExample.createCriteria();

        usercriteria.andEqualTo("username",username);
        usercriteria.andEqualTo("password",password);

        Users result=usersMapper.selectOneByExample(userExample);

        return result;
    }
}
